<template>
  <view class="tab-follow">
    <scroll-view 
      scroll-y 
      class="follow-scroll"
      :refresher-enabled="true"
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
    >
      <view class="follow-list">
        <view v-if="loading && followList.length === 0" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>

        <view v-else-if="!loading && followList.length === 0" class="empty-container">
          <text class="empty-emoji">👀</text>
          <text class="empty-text">还没有关注任何内容</text>
          <text class="empty-tip">去浏览感兴趣的内容吧~</text>
        </view>

        <view v-else class="follow-items">
          <view 
            class="follow-item" 
            v-for="item in followList" 
            :key="item.id"
            @tap="goToDetail(item)"
          >
            <view class="item-image" v-if="item.image">
              <image :src="item.image" mode="aspectFill" class="cover-img" />
            </view>
            <view class="item-image placeholder" v-else>
              <text class="placeholder-emoji">{{ getTypeEmoji(item.type) }}</text>
            </view>

            <view class="item-content">
              <view class="item-header">
                <text class="item-title">{{ item.title || item.name }}</text>
                <view class="type-badge">
                  <text class="badge-text">{{ getTypeName(item.type) }}</text>
                </view>
              </view>
              
              <text class="item-description" v-if="item.synopsis || item.remark">
                {{ item.synopsis || item.remark }}
              </text>
              
              <view class="item-footer">
                <text class="follow-time">{{ formatTime(item.createTime) }}</text>
                <view class="action-buttons">
                  <view class="unfollow-btn" @tap.stop="unfollowItem(item)">
                    <text class="unfollow-text">取消关注</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view v-if="loadingMore" class="loading-more">
          <text class="loading-more-text">加载更多...</text>
        </view>
        
        <view v-if="noMore && followList.length > 0" class="no-more">
          <text class="no-more-text">没有更多了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import sheep from '@/sheep';

const loading = ref(false);
const loadingMore = ref(false);
const refresherTriggered = ref(false);
const followList = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const noMore = ref(false);

const resetData = () => {
  followList.value = [];
  pageNum.value = 1;
  noMore.value = false;
};

const loadFollowList = async (isLoadMore = false) => {
  if (loading.value || (isLoadMore && (loadingMore.value || noMore.value))) return;
  
  try {
    if (isLoadMore) {
      loadingMore.value = true;
    } else {
      loading.value = true;
    }

    const response = await sheep.$api.noAuth.getFollowList();
    
    if (response && response.content) {
      const newList = response.content.map(item => ({
        ...item,
        image: getItemImage(item)
      }));
      
      if (isLoadMore) {
        followList.value = [...followList.value, ...newList];
      } else {
        followList.value = newList;
      }
      
      noMore.value = newList.length < pageSize.value || response.last === true;
      
      if (!noMore.value) {
        pageNum.value += 1;
      }
    } else {
      if (!isLoadMore) {
        followList.value = [];
      }
      noMore.value = true;
    }
  } catch (error) {
    sheep.$helper.toast('加载失败，请稍后重试');
    noMore.value = true;
  } finally {
    loading.value = false;
    loadingMore.value = false;
    refresherTriggered.value = false;
  }
};

const getItemImage = (item) => {
  let imagePath = null;
  
  if (item.pics) {
    const picArray = item.pics.split(',').filter(pic => pic && pic !== 'null' && pic.trim() !== '');
    if (picArray.length > 0) {
      imagePath = picArray[0].trim();
    }
  }
  
  if (!imagePath && item.pic && item.pic !== 'null') {
    imagePath = item.pic.trim();
  }
  
  if (!imagePath) return null;
  
  if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
    return imagePath;
  }
  
  const baseUrl = sheep.$platform.baseUrl || '';
  return baseUrl + (imagePath.startsWith('/') ? imagePath : '/' + imagePath);
};

const getTypeName = (type) => {
  const typeMap = {
    2: '推荐',
    3: '视频', 
    4: '民宿',
    5: '体验',
    6: '驿站',
    7: '文旅'
  };
  return typeMap[type] || '未知';
};

const getTypeEmoji = (type) => {
  const emojiMap = {
    2: '📝',
    3: '🎬',
    4: '🏠',
    5: '🎯',
    6: '🚉',
    7: '🗺️'
  };
  return emojiMap[type] || '📄';
};

const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now - date;
  
  if (diff < 60000) return '刚刚';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`;
  
  return date.toLocaleDateString('zh-CN');
};

const unfollowItem = async (item) => {
  try {
    await sheep.$api.noAuth.unfollowById(item.id);
    
    const index = followList.value.findIndex(followItem => followItem.id === item.id);
    if (index > -1) {
      followList.value.splice(index, 1);
    }
  } catch (error) {
    sheep.$helper.toast('取消关注失败，请稍后重试');
  }
};

const goToDetail = (item) => {
  const routeMap = {
    2: '/pages/recommend-detail',
    3: '/pages/video-detail',
    4: '/pages/hotel-detail',
    5: '/pages/experience-detail',
    6: '/pages/station-detail',
    7: '/pages/tourism-detail'
  };
  
  const route = routeMap[item.type];
  if (route) {
    sheep.$router.go(`${route}?id=${item.id}`);
  }
};

const onRefresh = () => {
  refresherTriggered.value = true;
  resetData();
  loadFollowList();
};

const onLoadMore = () => {
  if (!noMore.value && !loadingMore.value) {
    loadFollowList(true);
  }
};

onMounted(() => {
  loadFollowList();
});
</script>

<style lang="scss" scoped>
$primary-color: #8B4513;
$secondary-color: #DAA520;
$text-dark: #333;
$text-light: #666;
$border-color: #e0e0e0;

.tab-follow {
  height: 100%;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.follow-scroll {
  flex: 1;
  background: #f8f9fa;
  height: 100%;
}

.follow-list {
  padding: 20rpx;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  
  .loading-text {
    font-size: 28rpx;
    color: $text-light;
  }
  
  .empty-emoji {
    font-size: 80rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 30rpx;
    color: $text-dark;
    margin-bottom: 15rpx;
  }
  
  .empty-tip {
    font-size: 26rpx;
    color: $text-light;
  }
}

.follow-items {
  .follow-item {
    display: flex;
    background: white;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
    
    .item-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      overflow: hidden;
      margin-right: 30rpx;
      flex-shrink: 0;
      
      .cover-img {
        width: 100%;
        height: 100%;
      }
      
      &.placeholder {
        background: #f0f0f0;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .placeholder-emoji {
          font-size: 40rpx;
        }
      }
    }
    
    .item-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .item-header {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        margin-bottom: 15rpx;
        
        .item-title {
          flex: 1;
          font-size: 30rpx;
          font-weight: 500;
          color: $text-dark;
          line-height: 1.4;
          margin-right: 20rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .type-badge {
          padding: 8rpx 16rpx;
          background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
          border-radius: 20rpx;
          flex-shrink: 0;
          
          .badge-text {
            font-size: 20rpx;
            color: white;
          }
        }
      }
      
      .item-description {
        font-size: 26rpx;
        color: $text-light;
        line-height: 1.5;
        margin-bottom: 20rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      
      .item-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: auto;
        
        .follow-time {
          font-size: 24rpx;
          color: $text-light;
        }
        
        .action-buttons {
          .unfollow-btn {
            padding: 12rpx 24rpx;
            background: #fff2f2;
            border: 1rpx solid #ffccc7;
            border-radius: 20rpx;
            
            .unfollow-text {
              font-size: 24rpx;
              color: #ff4d4f;
            }
            
            &:active {
              background: #ffe7e7;
            }
          }
        }
      }
    }
  }
}

.loading-more,
.no-more {
  text-align: center;
  padding: 40rpx 0;
  
  .loading-more-text,
  .no-more-text {
    font-size: 26rpx;
    color: $text-light;
  }
}
</style> 